package com.intelligent.ispc.client.core.controller;

import com.intelligent.ispc.common.utils.StringUtils;
import com.intelligent.ispc.constant.AppConstant;
import com.intelligent.ispc.core.dto.SysConfigDto;
import com.intelligent.ispc.core.service.SysConfigService;
import com.intelligent.ispc.utils.ApplicationPathUtil;
import com.itextpdf.text.log.Logger;
import com.itextpdf.text.log.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * Created by hao on 2016/9/18.
 */
@Component
public class SystemConfigController {
    private final Logger logger = LoggerFactory.getLogger(SystemConfigController.class);

    @Autowired
    private SysConfigService sysConfigService;

    public void savePath(String scriptPath, String exportPath) {
        logger.info("save system path");
        SysConfigDto sysConfigDto = new SysConfigDto();
        SysConfigDto sysConfigDto1 = new SysConfigDto();
        sysConfigDto.setName(AppConstant.SYSTEM_CONFIG_SCRIPT_PATH);
        sysConfigDto.setValue(scriptPath);
        sysConfigDto1.setName(AppConstant.SYSTEM_CONFIG_FIELD_PATH);
        sysConfigDto1.setValue(exportPath);
        sysConfigService.update(sysConfigDto);
        sysConfigService.update(sysConfigDto1);
    }

    public boolean validatePath(String name) {
        if (StringUtils.isBlank(name)) {
            return false;
        }
        if (sysConfigService.findByName(name) == null) {
            return false;
        }
        return true;
    }

    public void updatePath(String name, String value) {
        logger.info("update system path");
        SysConfigDto sysConfigDto = sysConfigService.findByName(name);
        if (sysConfigDto == null) {
            return;
        }
        sysConfigDto.setValue(value);
        sysConfigService.update(sysConfigDto);
    }

    public String getPath(String name) {
        String result = ApplicationPathUtil.getCanonicalPath();
        if (StringUtils.isBlank(name)) {
            return result;
        }
        SysConfigDto dto = sysConfigService.findByName(name);
        if (dto == null) {
            return result;
        }

        if (StringUtils.isNotBlank(dto.getValue())) {
            return dto.getValue();
        } else {
            if (dto.getName().equals(AppConstant.SYSTEM_CONFIG_FIELD_PATH)) {
                result += AppConstant.PATH_EXPORT;
            } else if (dto.getName().equals(AppConstant.SYSTEM_CONFIG_SCRIPT_PATH)) {
                return ApplicationPathUtil.getPath(AppConstant.PATH_SCRIPT, AppConstant.PATH_SCRIPT_FILENAME);
//                result += AppConstant.PATH_SCRIPT + "/" + AppConstant.PATH_SCRIPT_FILENAME;
            }
        }

        return result;
    }
}
